//
//  MYPictureSelectorController.swift
//  Sina
//
//  Created by 王亮龙1 on 16/5/30.
//  Copyright © 2016年 lianglong. All rights reserved.
//

import UIKit
import SnapKit
import HMImagePicker


//定义显示图片的信息
private let colCount: CGFloat = 4
private let margin: CGFloat = 3
private let maxImageCount = 4
private let itemWidth: CGFloat = (ScreenWidth - (colCount + 1) * margin) / colCount

//定义可重用标识符
private let PictureCellId = "PictureCellId"


class MYPictureSelectorController: UICollectionViewController {
    
    //声明数组,用来记录选择的照片,便于下次选取
    lazy var selectedAsset: [PHAsset] = [PHAsset]()
    
    //定义图片的数组
    lazy var images: [UIImage] = [UIImage]()
    
    //必须用这个,因为MYComposeViewController中懒加载VC时会调用系统的init(),带参数的系统不会调用,就会导致,在父视图控制器不能加载子视图控制器
    init() {
        
        let layout = UICollectionViewFlowLayout()
        //布局属性
        layout.itemSize = CGSizeMake(itemWidth, itemWidth)
        layout.minimumLineSpacing = margin
        layout.minimumInteritemSpacing = margin
        //设置每组的内边距
        layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
        
        super.init(collectionViewLayout: layout)
        //测试颜色
        self.collectionView?.backgroundColor = UIColor.whiteColor()
        
        self.collectionView?.registerClass(MYPictureSelectorCell.self, forCellWithReuseIdentifier: PictureCellId)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

}



extension MYPictureSelectorController: MYPictureSelectorCellDelegate {
    
    @objc func userWillAddPicture() {
        //如果没有访问权限
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            return
        }
        
        //实话图片选择器
        let picker = HMImagePickerController(selectedAssets: selectedAsset)
        picker.pickerDelegate = self
        picker.targetSize = CGSize(width: 600, height: 600)
        //最大图片数
        picker.maxPickerCount = maxImageCount
        //MARK:modal出图片选择器
        presentViewController(picker, animated: true, completion: nil)
        
    }
    
    @objc func userWillDeletePicture(cell: MYPictureSelectorCell) {
        
        guard let indexPath = collectionView?.indexPathForCell(cell) else {
            return
        }
        
        images.removeAtIndex(indexPath.item)
        
        //用来记录已选择图片也要删元素,不然在控制器删除后,图片选择器那边还是会有
        selectedAsset.removeAtIndex(indexPath.item)
        
        //必须刷新数据.不然删除了,界面不会有变化
        collectionView?.reloadData()
    }
}


//遵守图片选择器的协议
extension MYPictureSelectorController: HMImagePickerControllerDelegate {
    
    func imagePickerController(picker: HMImagePickerController, didFinishSelectedImages images: [UIImage], selectedAssets: [PHAsset]?) {
        
        //两个数组都要赋值
        //在这里框架会把选择图片添加到,框架的图片数组中,赋值后自己的图片数组也就有了元素
        self.images = images
        self.selectedAsset = selectedAssets!
        
        //要在跳转控制器前,就要刷新数据,不然界面会在出现后出现变化,界面效果不好
        self.collectionView?.reloadData()
        
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    
    
}



extension MYPictureSelectorController {
    
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        //在达到最大图片数,就不让界面的cell数加1
        //加1,是因为,刚开始cell数要是为零,界面什么都不会展示,黑色
        let delta = images.count == maxImageCount ? 0 : 1
        //如果等于最大图片数,返回最大图片数,否则加1(没有图片),
        return images.count + delta
    }
    
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(PictureCellId, forIndexPath: indexPath) as! MYPictureSelectorCell
        //设置代理对象
        cell.selectedDelegate = self
        
        cell.backgroundColor = randomColor()
        
        //因为之前返回cell数,为了防止界面刚开始images.count等于0,造成的黑屏,所以人为加1,就造成了cell数比数组的count多一,也就是造成了数组越界,会导致程序崩溃,所以这里在两个索引相等时,把image赋值为nil
        if indexPath.item == images.count {
            cell.image = nil
        } else {
            cell.image = images[indexPath.item]
        }
        
        
        return cell
    }
}



@objc protocol MYPictureSelectorCellDelegate: NSObjectProtocol {
    
    optional func userWillAddPicture()
    optional func userWillDeletePicture(cell: MYPictureSelectorCell)
}




//自定义cell
class MYPictureSelectorCell: UICollectionViewCell {
    
    weak var selectedDelegate: MYPictureSelectorCellDelegate?
    
    var image: UIImage? {
        didSet {
            
            //没有图片时,删除按钮隐藏
           deleteBtn.hidden = image == nil
            addBtn.setImage(image, forState: .Normal)
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //两个按钮的点击方法
    @objc private func addBtnClick() {
        
        //只有在没有图片时,才能添加新图片,解决了cell.image赋值后还能点击的,然后继续添加图片,能超过最大图片数的bug
        if image != nil {
            return
        }
        selectedDelegate?.userWillAddPicture?()
    }
    
    @objc private func deleteBtnClick() {
    
        selectedDelegate?.userWillDeletePicture?(self)
    }
    
    
    //布局
    private func setupUI() {
        contentView.addSubview(addBtn)
        contentView.addSubview(deleteBtn)
        
        //设置约束
        addBtn.snp_makeConstraints { (make) in
            make.edges.equalTo(contentView.snp_edges)
        }
        
        deleteBtn.snp_makeConstraints { (make) in
            make.top.right.equalTo(contentView)
        }
        
        
        addBtn.addTarget(self, action: #selector(MYPictureSelectorCell.addBtnClick), forControlEvents: .TouchUpInside)
        deleteBtn.addTarget(self, action: #selector(MYPictureSelectorCell.deleteBtnClick), forControlEvents: .TouchUpInside)
    
    }
    
    
    //懒加载子控件
    private lazy var addBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "compose_pic_add"), forState: .Normal)
        btn.imageView?.contentMode = .ScaleAspectFill
        btn.imageView?.clipsToBounds = true
        
        return btn
    }()
    
    
    private lazy var deleteBtn: UIButton = {
        
        let btn = UIButton()
        
        btn.setBackgroundImage(UIImage(named: "compose_photo_close"), forState: .Normal)
        
        return btn
    }()
    
    
}
